package cn.coopen.italktv.demo02_otherview.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.PopupMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import cn.coopen.italktv.demo02_otherview.R;


/**
 * 作者： qing
 * 创建日期：2018/2/5
 * 功能描述：PopWindow的使用呢
 */

public class PopFragment extends Fragment {

	private AppCompatButton listBtn;
	private AppCompatButton menuBtn;
	private ListAdapter listAdapter;

	public static PopFragment newInstance() {
		PopFragment fragment = new PopFragment();
		return fragment;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_page, container, false);
		listBtn = view.findViewById(R.id.listpop_btn);
		menuBtn = view.findViewById(R.id.menupop_btn);
		intiData();
		setClick();
		return view;
	}

	private void intiData() {
		String[] textArray={
				"北京",
				"上海",
				"天津",
				"广州",
				"广州",
				"广州",
				"广州"
		};
		listAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,textArray);
	}

	private void setClick() {
		listBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				showListPop();
			}
		});

		menuBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				showMenuPop();
			}


		});
	}

	private void showMenuPop() {
		final PopupMenu popupMenu = new PopupMenu(getContext(), menuBtn);
		popupMenu.getMenuInflater().inflate(R.menu.main,popupMenu.getMenu());
		popupMenu.show();
		popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				popupMenu.dismiss();
				return false;
			}
		});
	}

	private void showListPop() {
		final ListPopupWindow listPopupWindow = new ListPopupWindow(getActivity());
		listPopupWindow.setAnchorView(listBtn);
		listPopupWindow.setWidth(150);
		listPopupWindow.setHeight(300);
		listPopupWindow.setAdapter(listAdapter);
		listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
				listPopupWindow.dismiss();
			}
		});
		listPopupWindow.show();
	}
}
